import java.util.HashSet;

/**
 * @program: LeetCode
 * @description: LeetCode : 202. 快乐数
 * @author: WXY
 * @create: 2023-01-14 21:29
 * @Version 1.0
 **/
public class Num202_isHappy {
    public static boolean isHappy1(int n) {
        HashSet<Integer> set = new HashSet<>();
        while (n != 1) {
            set.add(n);
            n = sumOfEachNumber(n);
            if (set.contains(n)) {
                return false;
            }
        }
        return true;

    }

    private static int sumOfEachNumber(int n) {
        int sum = 0;
        while (n > 0) {
            sum += (n % 10) * (n % 10);
            n /= 10;
        }
        return sum;
    }

    public static boolean isHappy(int n) {
        int fast = sumOfEachNumber(n);
        int slow = n;
        while (fast != 1 && fast != slow) {
            slow = sumOfEachNumber(slow);
            fast = sumOfEachNumber(sumOfEachNumber(fast));
        }
        return fast == 1;
    }

    public static void main(String[] args) {
        boolean happy = isHappy(4);
        System.out.println(happy);
    }
}
